-module(binary_writer).
-export([write/1]).
-export([encode/1]).
-export([decode/1]).

write(Args)->
    [Template, Message, BinaryFileName] = Args,
    Module = list_to_atom(Template),
    Function = list_to_atom(Message),
    Bin = term_to_binary(apply(Module,Function,[])),
    ok = file:write_file(BinaryFileName, Bin).

encode(Args)->
    [ModuleName, BinaryFileName] = Args,
    Module = list_to_atom(ModuleName),
    {ok, Bin} = file:read_file(BinaryFileName),
    Term = binary_to_term(Bin),
    PduName = string:concat(ModuleName, "-PDU"),
    PDU = list_to_atom(PduName),
    {ok, MessageBinary} = apply(Module, encode, [PDU, Term]),
    WriteFileName = string:concat(BinaryFileName, ".enc"),
    ok = file:write_file(WriteFileName, MessageBinary).

decode(Args)->
    [ModuleName, InBinaryFileName, OutBinaryFileName] = Args,
    Module = list_to_atom(ModuleName),
    {ok, Bin} = file:read_file(InBinaryFileName),
    PduName = string:concat(ModuleName, "-PDU"),
    PDU = list_to_atom(PduName),
    {ok, Message} = apply(Module, decode, [PDU, Bin]),
    MessageBinary = term_to_binary(Message),
    ok = file:write_file(OutBinaryFileName, MessageBinary).
